# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

# library(MetaboAnalystR)
library(plyr)
library(ggplot2)
library(dplyr)
library(tidyr)
library(tibble)
library(gridExtra)
library(ggpubr)
library(egg)
library(lemon)
library(optparse)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
make_option("--mc", default = "meta_color.txt", type = "character", help = "metabolite color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
select(c("SampleID", "ClassNote"))

data <- read.csv(opt$i, header = T, check.names = F, stringsAsFactors = F) %>%
    select(- c("HMDB", "KEGG")) %>%
    filter(! startsWith(Name, "Unknown")) %>%
    mutate(Name = factor(Name, levels = unique(Name))) %>%
    select(- c("Class")) %>%
    gather("SampleID", "Value", - Name, factor_key = T) %>%
    spread(Name, "Value") %>%
    inner_join(sampleInfo, by = c("SampleID")) %>%
    group_by(ClassNote) %>%
    summarise_at(vars(- "SampleID"), median) %>%
    mutate_at(vars(- "ClassNote"), scale) %>%
    column_to_rownames("ClassNote")

head(data)

parent <- "z-score"
createWhenNoExist(parent)
fileName <- paste0(parent, "/median_z-score.csv")

write.csv(data, fileName)

